<template>
  <div>
    <el-drawer
      v-model="dialogVisible"
      :title="dialogStatus==='create'?'添加升级包': (dialogStatus === 'view' ? '查看升级包' : '编辑升级包')"
      width="600px"
      @close="reset"
    >
      <div class="scene-dialog">
        <el-form 
          ref="formRef"
          :model="formItem" 
          :rules="rules"
          label-width="100"
          label-position="top"
          :disabled="!isDisabled"
        >
          <el-form-item label="升级包名称" prop="pkgName">
            <el-input v-model="formItem.pkgName" />
          </el-form-item>

          <el-form-item label="所属设备类型" prop="equipType">
            <el-select 
                v-model="formItem.equipType" 
                clearable
                placeholder="请选择"
              >
                <el-option 
                  v-for="item in equipOption"
                  :label="item.name" 
                  :value="+item.value" 
                />
            </el-select>
          </el-form-item>

          <el-form-item label="升级包版本号" prop="pkgVersion">
            <el-input v-model="formItem.pkgVersion" />
          </el-form-item>

          <el-form-item label="上传升级包" prop="pkgUrl" >
            <el-upload
              ref="upload"
              :file-list="formItem.uploadList"
              accept=".bin, .OTA," 
              :show-file-list="true"
              :action="`/base-api/acq-ota/upload`" 
              :limit="1"
              :headers="headers" 
              :on-success="(data: any, uploadFile: any)=>handleUploadSuccess(data, uploadFile)"
              :on-error="handleUploadError"
              :on-remove="removeItem"
              :on-exceed="handleExceed"
              name="files"
              style="display: inline-block; margin: 0 10px 0 0; vertical-align: middle;"
              auto-upload
            >
              <el-button>
                上传文件
              </el-button>
              <template #tip>
                <div class="el-upload__tip">
                  支持格式：.bin .OTA
                </div>
              </template>
            </el-upload>
          </el-form-item>

          <el-form-item label="升级包描述" prop="pkgDes">
            <el-input v-model="formItem.pkgDes" />
          </el-form-item>

          <el-form-item label="所属项目" prop="projectIds">
            <el-select 
              v-model="formItem.projectIds" 
              multiple
              collapse-tags
              collapse-tags-tooltip
              clearable
              placeholder="请选择"
            >
              <el-option 
                v-for="item in projectOption"
                :label="item.projectName" 
                :value="+item.id" 
              />
            </el-select>
          </el-form-item>

        </el-form>
      </div>
        
      <template #footer v-if="isDisabled">
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogStatus==='create'?createData():updateData()"
          >提交</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage, genFileId } from 'element-plus'
import { getToken } from '@/utils/user'
import { editOta, getDist, addOta, getProjectList } from '@/api/collect'
import { validate } from '@/utils/validate'

const isDisabled = ref(true)

const formRef = ref<any>(null)

const formItem = reactive({
  pkgName: '',
  equipType: '',
  pkgVersion: '',
  pkgUrl: '',
  pkgDes: '',
  uploadList: [],
  originName: '',
  projectIds: [],
})

const rules = reactive({
  pkgName: [{ required: true, message: '请输入', trigger: 'blur' }],
  equipType: [{ required: true, message: '请输入', trigger: 'blur' }],
  pkgVersion: [{ required: true, message: '请输入', trigger: 'blur' }],
  pkgUrl: [{ required: true, message: '请上传', trigger: 'change' }],
})

const dialogVisible = ref(false)
const dialogStatus = ref('create')

const equipOption = ref<any>([])

const getEquipList = () => {
  getDist('DC00011').then((res: any)=>{
    equipOption.value = res.data
  })
  .catch((err: any) => {
    console.error('err', err.msg)
  })
}

getEquipList()

// 文件上传
// 是否只读
// const readonly = computed(() => props.state == 'check')

const handleUploadSuccess = (data: any, uploadFile: any,) => {
  if (data.success == true) {
    // console.log('data', data)
    // TODO 回显用，后端字段修改 uploadUrl=>url, photoName=>name
    const params = {
      name: '',
      url: '',
    }
    // TODO 回显用，后端字段修改 uploadUrl=>url, photoName=>name
    params.url = data.data[0]
    params.name = uploadFile.name
    formItem.originName = uploadFile.name
    formItem.uploadList.push(params)
    // console.log('formItem.uploadPhotoDtoList', formItem.uploadPhotoDtoList)
    ElMessage.success(data.msg)
  } else {
    ElMessage.error(data.msg);
  }
}

const removeItem = (i: any) => {
  // console.log('remove-item', i)
  const removeIndex = formItem.uploadList.findIndex((item: any) => i.uploadUrl == item.uploadUrl)
  formItem.uploadList.splice(removeIndex, 1)
  // console.log('formItem.uploadPhotoDtoList', formItem.uploadPhotoDtoList)
}

const handleUploadError = (err: any) => {
  const message = JSON.parse(err.toString().replace('UploadAjaxError: ', '')).msg
  ElMessage.error(message)
}

const upload = ref()

const handleExceed = (files: any) => {
  upload.value!.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value!.handleStart(file)
  upload.value!.submit()
}

const token = getToken();

const headers = { Authorization: `${token}` }

const projectOption = ref<any>([])  

const handleProjectList = () => {
  getProjectList().then((res: any)=>{
    projectOption.value = res.data
  })
  .catch((err: any) => {
    console.error('err', err.msg)
  })
}

handleProjectList()

// 重置
const reset = () => {
  if (!formRef) return
  formRef.value.resetFields()
  formItem.uploadList = []
  isDisabled.value = false
}

const emit = defineEmits(['listChange'])

const createData = async () => {
  formItem.pkgUrl = formItem.uploadList[0]?.url
  const valid = await validate(formRef)
  if (valid) {
    addOta(formItem)
    .then(() => {
      // TODO use res data
      emit('listChange')
      dialogVisible.value = false
      ElMessage.success('创建成功！')
    })
    .catch((err:any) => {
      dialogVisible.value = false
      ElMessage.error('创建失败！'+ err.msg)
    })
  }
}

const updateData = async () => {
  const valid = await validate(formRef)
  if (valid) {
    editOta(formItem)
    .then(() => {
      // TODO use res data
      emit('listChange')
      dialogVisible.value = false
      ElMessage.success('更新成功！')
    })
    .catch((err:any) => {
      dialogVisible.value = false
      ElMessage.error('更新失败！'+ err.msg)
    })
  }
}

defineExpose({ dialogVisible, formItem, isDisabled, dialogStatus, reset })
</script>
<style lang="scss" scoped>
.el-upload__tip {
  line-height: 20px;
}
// :deep(.el-drawer__header) {
//   margin-bottom: 0;
// }
</style>
